package com.test.textGame.transaction;

import com.test.textGame.enums.MqLogTypeEnum;
import com.test.textGame.mq.RabbitMqRedisProducer;
import com.test.textGame.service.MqFailLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MasterTransactionListener implements TransactionListener {

    @Autowired
    private RabbitMqRedisProducer rabbitMqRedisProducer;
    @Autowired
    private MqFailLogService mqFailLogService;

    /**
     * 发送half msg 执行本地事务（给redis发消息）
     * @param message
     * @param o
     * @return
     */
    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("开始执行本地事务....");
        LocalTransactionState state;
        String msg = new String(message.getBody());
        try{
            rabbitMqRedisProducer.sendScoreList(msg);
            // 返回commit后，消息能被消费者消费
            state = LocalTransactionState.COMMIT_MESSAGE;
            log.info("本地事务已提交。{}",message.getTransactionId());
        }catch (Exception e){
            log.info("给redis发消息失败e:"+e);
            //记录异常的事务
            mqFailLogService.transactionLog(MqLogTypeEnum.SEND_REDIS_FAIL, msg, message.getTransactionId());
            state = LocalTransactionState.ROLLBACK_MESSAGE;
        }
        return state;
    }

    /**
     * broker回查事务状态
     * @param messageExt
     * @return
     */
    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {

        // 回查多次失败 人工补偿
        log.info("开始回查本地事务状态。{}",messageExt.getTransactionId());
        LocalTransactionState state;
        String transactionId = messageExt.getTransactionId();
        if (mqFailLogService.countByTransactionId(transactionId) > 0){
            state = LocalTransactionState.COMMIT_MESSAGE;
        }else {
            state = LocalTransactionState.UNKNOW;
        }
        log.info("结束本地事务状态查询：{}",state);
        return state;
    }
}